package jmine.tec.report.impl.table.pdf;

import java.math.BigDecimal;

import jmine.tec.report.api.table.ReportCell;
import jmine.tec.report.impl.table.RendererParameterInterface;
import jmine.tec.report.impl.table.ReportTableBuilder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import bancosys.tec.utils.formatter.NumberFormatter;

import com.lowagie.text.Element;

/**
 * Implementação default de formatter de células de relatório
 * 
 * @author lundberg
 */
public class NumberCellPDFRenderer extends AbstractCellPDFRenderer {
    private static final Log LOG = LogFactory.getLog(NumberCellPDFRenderer.class);

    /**
     * {@inheritDoc}
     */
    public String getRendererType() {
        return ReportTableBuilder.TYPE_NUMBER;
    }

    /**
     * {@inheritDoc}
     */
    public String getFormattedString(ReportCell cell) {
        return NumberFormatter.formatDecimalNumber(this.getBigDecimalValue(cell), this.getDecimals(cell));
    }

    /**
     * Retorna o número de casas decimais que deve ser utilizada na formatação
     * 
     * @param cell cell
     * @return integera
     */
    protected int getDecimals(ReportCell cell) {
        RendererParameterInterface rpi = new RendererParameterInterface(cell);
        Integer decimals = rpi.getDecimals();
        return (decimals != null) ? decimals : this.getBigDecimalValue(cell).scale();
    }

    /**
     * Tenta obter o valor da célula na forma de um BigDecimal
     * 
     * @param cell cell
     * @return BigDecimal
     */
    protected BigDecimal getBigDecimalValue(ReportCell cell) {
        if (cell.getValue() == null) {
            return null;
        } else if (cell.getValue() instanceof BigDecimal) {
            return (BigDecimal) cell.getValue();
        } else if (cell.getValue() instanceof Number) {
            return BigDecimal.valueOf(((Number) cell.getValue()).doubleValue());
        } else {
            try {
                return new BigDecimal(cell.getValue().toString());
            } catch (NumberFormatException e) {
                LOG.error("Nao foi possivel converter a celula de valor \"" + cell.getValue().toString() + "\" para BigDecimal", e);
                return null;
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected int getHorizontalAlignment(RendererParameterInterface rpi) {
        return Element.ALIGN_RIGHT;
    }
}
